#include "Process.h"

	void *wrapper_func(void *args)
	{
		Process *curThread = (Process *)args;
		curThread->run();
	}

	pthread_t Process::start() {
		// Initialize the thread itself
		if (pthread_create(&processThread, NULL, wrapper_func, this) != 0)
		{
			cerr << "Process thread creation failed" << endl;
			std::exit(1);
		}
		return processThread;
	}

	Process::Process(int pid, LibraryFunctions* libFunctions) :
		libraryFunctions(libFunctions), id (pid) {}

	Process::~Process() {}

	void Process::run() {
		while (true) {
			if (!commandsVectorsQueue.empty()) {
				executeCommand (commandsVectorsQueue.front());
			}
		}
	}
	void Process::exit() {
		int status;
		pthread_exit(&status);
	}

	//operated by run if there are commands to execute
	void Process::executeCommand(vector<string>* command) {
		if (command->size()>0 && command->at(0).compare("exit") == 0) {
			exit();
		} else {
			cout << libraryFunctions->processCommand(*command) << endl;
			commandsVectorsQueue.pop();
			delete command;
		}
	}

	//operated by the shell
	void Process::addCommand (vector<string>* commandVector){
		commandsVectorsQueue.push(commandVector);
	}
